package com.hmdp.service.impl;

import cn.hutool.core.bean.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.hmdp.dto.*;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //当前用户ID
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        if (isFollow){
            //关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean save = save(follow);
            if (save){
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
        }else {
            //删除
            boolean remove = remove(new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId));
            if (remove){
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        //是否关注该用户
        Long userId = UserHolder.getUser().getId();
        boolean isFollow = getOne(new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId)) != null;
        return Result.ok(isFollow);
    }
    //共同关注
    @Override
    public Result followCommonId(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        Set<String> setCommon = stringRedisTemplate.opsForSet().intersect(key, "follows:" + followUserId);
        if (setCommon == null || setCommon.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = setCommon.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOList = userService.listByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOList);
    }
}
